import 'package:bpb/db/db_helper.dart';
import 'package:bpb/framework/base/base_controller.dart';
import 'package:bpb/framework/utils/date_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:getwidget/getwidget.dart';
import 'package:intl/intl.dart';

import '../../common/CommonData.dart';

class AddController extends BaseController {
  var dateTimeLabel = "".obs;
  var currentLevel = "".obs;
  var currentLevelLabel = "".obs;

  var currentSYS = "110".obs;
  var currentDIA = "80".obs;
  var currentHeart = "70".obs;

  var bloodLevels =
      <Map<String, dynamic>>[
        {"level": CommonData.BLOOD_PRESSURE_HYPOTENSION, "color": const Color(0xffCCD9FA), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_NORMAL, "color": const Color(0xffD7EACA), "checked": true},
        {"level": CommonData.BLOOD_PRESSURE_ELEVATED, "color": const Color(0xffF7E3C4), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_HYPERTENSIVE1, "color": const Color(0xffF7CDC4), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_HYPERTENSIVE2, "color": const Color(0xffFFA49E), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_HYPERTENSIVE, "color": const Color(0xffE57373), "checked": false},
      ].obs;

  var measurementSite =
      <Map<String, dynamic>>[
        {"name": "Right Arm", "checked": true, "value": "right arm"},
        {"name": "Left Arm", "checked": false, "value": "left arm"},
        {"name": "Right Wrist", "checked": false, "value": "right wrist"},
        {"name": "Left Wrist", "checked": false, "value": "left wrist"},
      ].obs;

  var symptoms =
      <Map<String, dynamic>>[
        {"name": "None", "checked": true, "value": "none"},
        {"name": "Palpitations", "checked": false, "value": "palpitations"},
        {"name": "Dizziness", "checked": false, "value": "dizziness"},
        {"name": "Chest pain", "checked": false, "value": "chest pain"},
        {"name": "Headaches", "checked": false, "value": "headaches"},
      ].obs;

  var medication =
      <Map<String, dynamic>>[
        {"name": "No", "checked": true, "value": "no"},
        {"name": "Yes", "checked": false, "value": "yes"},
      ].obs;

  dynamic viewData; //传过来查看的数据

  @override
  void onInit() {
    super.onInit();
    dateTimeLabel.value = DateFormat('MMM d, y    HH:mm').format(DateTime.now());

    if (null != Get.arguments && Get.arguments.containsKey("data")) {
      viewData = Get.arguments["data"];

      ///回显sys
      int oldSys = viewData["sys"];
      currentSYS.value = oldSys.toString();

      ///回显dia
      int oldDia = viewData["dia"];
      currentDIA.value = oldDia.toString();

      ///回显pulse
      int oldPulse = viewData["pulse"];
      currentHeart.value = oldPulse.toString();

      ///===========================
      ///回显measurement_site

      String measurement_site = viewData["measurement_site"];
      showBack(measurement_site, measurementSite);

      ///====================================================================
      ///回显symptoms
      String symptomsText = viewData["symptoms"];
      showBack(symptomsText, symptoms);

      ///回显medication
      String medicationLabel = viewData["medication"];
      showBack(medicationLabel, medication);

      ///回显时间recordTime: 2025-06-19 17:42:19
      String recordTime = viewData["recordTime"];
      DateTime recordTimeDate = DateUtil.DF_YMDHMS.parse(recordTime);
      dateTimeLabel.value = DateFormat('MMM d, y    HH:mm').format(recordTimeDate);
    }

    onSysChanged(currentSYS.value);
    onDiaChanged(currentDIA.value);

  }

  void showBack(String oldValue, RxList<Map<String, dynamic>> showlist) {
    for (var e in showlist.value) {
      if (oldValue == e["value"]) {
        e["checked"] = true;
      } else {
        e["checked"] = false;
      }
    }
    showlist.value = List.of(showlist.value);
  }

  Color getLevelBorderColor(String level) {
    Color defaultColor = const Color(0xffD7EACA);
    Color resultColor = defaultColor;
    for (var element in bloodLevels.value) {
      Color color = element["color"] as Color;
      String xlevel = element["level"] as String;
      if (xlevel == level) {
        resultColor = color;
        break;
      }
    }
    return resultColor;
  }

  List<String> createBpRanges() {
    List<String> ranges = <String>[];
    for (int i = 20; i <= 300; i++) {
      ranges.add("${i}");
    }
    return ranges;
  }

  void onSysChanged(String v) {
    currentSYS.value = v;
    checkCurrentBloodPressureLevel(int.parse(currentSYS.value), int.parse(currentDIA.value));
  }

  void onDiaChanged(String v) {
    currentDIA.value = v;
    checkCurrentBloodPressureLevel(int.parse(currentSYS.value), int.parse(currentDIA.value));
  }

  void onHeartChanged(String v) {
    currentHeart.value = v;
  }

  //实时更新当前的血压水平
  checkCurrentBloodPressureLevel(int sys, int dia) {
    try {
      List<String> level = CommonData.getBloodPressureLevel(sys, dia);
      currentLevel.value = level[0];
      currentLevelLabel.value = level[1];
      for (var ele in bloodLevels.value) {
        if (ele["level"] == currentLevel.value) {
          ele["checked"] = true;
        } else {
          ele["checked"] = false;
        }
      }
      bloodLevels.value = List.of(bloodLevels.value);
    } catch (e) {}
  }

  Future<void> onSave(BuildContext context) async {
    int sys = int.parse(currentSYS.value);
    int dia = int.parse(currentDIA.value);
    int heart = int.parse(currentHeart.value);

    // dateTimeLabel.value = DateFormat('MMM d, y    HH:mm').format(DateTime.now());

    DateFormat df = DateFormat("yyyy-MM-dd");
    DateTime rightDateTime = DateFormat('MMM d, y    HH:mm').parse(dateTimeLabel.value);

    String date = df.format(rightDateTime);

    //==========================

    String measurement_site = getCheckedValue(measurementSite.value);
    String symptomsValue = getCheckedValue(symptoms.value);
    String medicationValue = getCheckedValue(medication.value);
    String time = DateFormat('yyyy-MM-dd HH:mm:dd').format(rightDateTime);

    if (viewData != null) {

      DBHelper.updateBpById(autoId: viewData["autoId"], sys: sys, dia: dia, heart: heart);
      GFToast.showToast("Update success!", context, toastPosition: GFToastPosition.CENTER);
      await Future.delayed(Duration(seconds: 1));
      Get.back();

    } else {
      int beforCount = await DBHelper.countRecords();
      DBHelper.insertDb(sys, dia, heart, date, time, measurement_site, symptomsValue, medicationValue);
      int afterCount = await DBHelper.countRecords();
      ///===================================
      // DBHelper.insertMockDataForLast7Days(400);//添加7天测试数据
      // DBHelper.insertMockDataForLast7Days2(10);
      debugPrint("现有条数:${afterCount}");
      if (afterCount > beforCount) {
        GFToast.showToast("Add success!", context, toastPosition: GFToastPosition.CENTER);
        await Future.delayed(Duration(seconds: 1));
        Get.back();
      }
    }
  }

  getCheckedValue(List<dynamic> values) {
    String value = "";
    for (var e in values) {
      if (e["checked"] == true) {
        value = e["value"] as String;
        break;
      }
    }
    return value;
  }
}
